#include<iostream>
using namespace std;



struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr && l2 == nullptr) return nullptr;
        else if (l1 == nullptr) return l2;
        else if (l2 == nullptr) return l1;
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        ListNode* root = new ListNode(-1, nullptr);
        ListNode* rCur = root;
        int tmpDigit = 0;
        while (cur1 != nullptr && cur2 != nullptr) {
            if (tmpDigit > 9) {
                tmpDigit = cur1->val + cur2->val + 1;
            }
            else {
                tmpDigit = cur1->val + cur2->val;
            }
            ListNode* newNode = new ListNode(tmpDigit % 10, nullptr);
            rCur->next = newNode; rCur = rCur->next;
            cur1 = cur1->next; cur2 = cur2->next;
        }
        while (cur1 != nullptr) {
            if (tmpDigit > 9) {
                tmpDigit = cur1->val + 1;
            }
            else {
                tmpDigit = cur1->val;
            }
            ListNode* newNode = new ListNode(tmpDigit % 10, nullptr);
            rCur->next = newNode; rCur = rCur->next;
            cur1 = cur1->next;
        }
        while (cur2 != nullptr) {
            if (tmpDigit > 9) {
                tmpDigit = cur2->val + 1;
            }
            else {
                tmpDigit = cur2->val;
            }
            ListNode* newNode = new ListNode(tmpDigit % 10, nullptr);
            rCur->next = newNode; rCur = rCur->next;
            cur2 = cur2->next;
        }
        if (tmpDigit > 9) {
            ListNode* newNode = new ListNode(1, nullptr);
            rCur->next = newNode; rCur = rCur->next;
        }
        return root->next;
    }
};

